import { isEmpty } from 'ramda';
import { Suspense, lazy, useMemo } from 'react';
import { Navigate, Outlet } from 'react-router-dom';

import { Iconify } from '@/components/icon';
import { CircleLoading } from '@/components/loading';
import { useUserPermission } from '@/store/userStore';
import ProTag from '@/theme/antd/components/tag';
import { flattenTrees } from '@/utils/tree';

import { Permission } from '@/types/entity';
import { BasicStatus, PermissionType } from '@/types/enum';
import { AppRouteObject } from '@/types/router';
import {
  KNOW_BASE_APPROVAL_PERMISSION,
  KNOW_API_PERMISSION,
  KNOW_EXTENSION_PERMISSION,
  KNOW_PERMISSION,
  DATASET_PERMISSION,
  WORK_BASE_PERMISSION,
  WORK_BASE_PERMISSION_V1,
} from '@/_mock/assets';
import usePermission from '@/hooks/event/usePermission';
import {
  useApiFlag,
  useConfigState,
  useDatasetFlag,
  useInitializeData,
  useInitializeKG,
} from '@/store/configStore';
import { LicenseEditionEnum } from '@/common';
import useInitialize from '@/hooks/event/use-initialize';
import { appRoutes } from '@/pages/tiangong-ai/routes';

// 使用 import.meta.glob 获取所有路由组件
const entryPath = '/src/pages';
const pages = import.meta.glob('/src/pages/**/*.tsx');
export const pagesSelect = Object.entries(pages).map(([path]) => {
  const pagePath = path.replace(entryPath, '');
  return {
    label: pagePath,
    value: pagePath,
  };
});

// 构建绝对路径的函数
function resolveComponent(path: string) {
  return pages[`${entryPath}${path}`];
}

// 工作台路由
export function useWorkBasePermissionRoutes() {
  const permissions = WORK_BASE_PERMISSION;
  return useMemo(() => {
    const flattenedPermissions = flattenTrees(permissions as Permission[]);
    const permissionRoutes = transformPermissionToMenuRoutes(
      permissions || [],
      flattenedPermissions,
    );
    return [...permissionRoutes];
  }, [permissions]);
}

// Legacy工作台路由
export function useWorkLegacyPermissionRoutes() {
  const permissions = WORK_BASE_PERMISSION_V1
  return useMemo(() => {
    const flattenedPermissions = flattenTrees(permissions as Permission[]);
    const permissionRoutes = transformPermissionToMenuRoutes(
      permissions || [],
      flattenedPermissions,
    );
    return [...permissionRoutes];
  }, [permissions]);
}

/**
 * return routes about permission
 */
export function usePermissionRoutes() {
  // 切换回静态路由
  // return useMemo(() => {
  //   return getRoutesFromModules();
  // }, []);
  // const permissions = useUserPermission();

  // const { isAdmin } = usePermission();
  // const datasetFlag = useDatasetFlag();
  // const apiFlag = useApiFlag();
  // const permissions = [
  //   ...GUEST_PERMISSION,
  //   ...(isAdmin || apiFlag ? DATASET_FLAG_PERMISSION : []),
  //   ...(isAdmin ? PERMISSION_LIST : []),
  // ];
  const permissions = useUserPermission();

  return useMemo(() => {
    const flattenedPermissions = flattenTrees(permissions!);
    const permissionRoutes = transformPermissionToMenuRoutes(
      permissions || [],
      flattenedPermissions,
    );
    return [...permissionRoutes];
  }, [permissions]);
}

// import { KNOW_API_PERMISSION, KNOW_EXTENSION_PERMISSION, KNOW_PERMISSION } from '@/_mock/assets';
// import usePermission from '@/hooks/event/usePermission';
// import { useApiFlag, useDatasetFlag } from '@/store/configStore';

export function useKnowPermissionRoutes() {
  const { isAdmin } = usePermission();
  const initializeData = useInitializeData();
  const apiFlag = useApiFlag();
  const datasetFlag = useDatasetFlag();
  const { enable_knowledge_governance } = useInitialize();

  const permissions = useMemo(() => {
    if (true) {
      return [
        ...DATASET_PERMISSION,
        ...KNOW_PERMISSION,
        ...KNOW_API_PERMISSION,
        ...KNOW_BASE_APPROVAL_PERMISSION,
        ...KNOW_EXTENSION_PERMISSION
      ];
    }

    const isBasicEdition = initializeData?.license_edition === LicenseEditionEnum.basic;
    const isCustomEdition = initializeData?.license_edition === LicenseEditionEnum.custom;
    const knowledgeGovEnabled = !isBasicEdition && enable_knowledge_governance && datasetFlag;
    const apiAccessAllowed = isCustomEdition && (isAdmin || apiFlag);
    const extensionAccessAllowed = !isBasicEdition && isAdmin;

    return [
      ...DATASET_PERMISSION,
      ...(knowledgeGovEnabled ? KNOW_PERMISSION : []),
      ...(apiAccessAllowed ? KNOW_API_PERMISSION : []),
      ...(apiAccessAllowed ? KNOW_BASE_APPROVAL_PERMISSION : []),
      ...(extensionAccessAllowed ? KNOW_EXTENSION_PERMISSION : []),
    ];
  }, [isAdmin, initializeData, apiFlag, datasetFlag, enable_knowledge_governance])

  return useMemo(() => {
    const flattenedPermissions = flattenTrees(permissions as Permission[]);
    const permissionRoutes = transformPermissionToMenuRoutes(
      permissions || [],
      flattenedPermissions,
    );
    return [...permissionRoutes];
  }, [permissions]);
}

/**
 * transform Permission[] to  AppRouteObject[]
 * @param permissions
 * @param parent
 */
function transformPermissionToMenuRoutes(
  permissions: Permission[],
  flattenedPermissions: Permission[],
) {
  return permissions.map((permission) => {
    const {
      route,
      type,
      label,
      icon,
      order,
      hide,
      hideTab,
      hideHeader,
      status,
      frameSrc,
      newFeature,
      component,
      parentId,
      children = [],
    } = permission;

    const appRoute: AppRouteObject = {
      path: route,
      meta: {
        label,
        key: getCompleteRoute(permission, flattenedPermissions),
        hideMenu: !!hide,
        hideHeader: !!hideHeader,
        hideTab,
        disabled: status === BasicStatus.DISABLE,
      },
    };

    if (order) appRoute.order = order;
    if (icon) appRoute.meta!.icon = icon;
    if (frameSrc) appRoute.meta!.frameSrc = frameSrc;

    if (newFeature) {
      appRoute.meta!.suffix = (
        <ProTag color="cyan" icon={<Iconify icon="solar:bell-bing-bold-duotone" size={14} />}>
          NEW
        </ProTag>
      );
    }

    if (type === PermissionType.CATALOGUE) {
      appRoute.meta!.hideTab = true;
      if (!parentId) {
        appRoute.element = (
          <Suspense fallback={<CircleLoading />}>
            <Outlet />
          </Suspense>
        );
      }
      appRoute.children = transformPermissionToMenuRoutes(children, flattenedPermissions);

      if (!isEmpty(children)) {
        appRoute.children.unshift({
          index: true,
          element: <Navigate to={children[0].route} replace />,
        });
      }
    } else if (type === PermissionType.MENU) {
      const Element = lazy(resolveComponent(component!) as any);
      if (frameSrc) {
        appRoute.element = <Element src={frameSrc} />;
      } else {
        appRoute.element = (
          <Suspense fallback={<CircleLoading />}>
            <Element />
          </Suspense>
        );
      }
    }

    return appRoute;
  });
}

/**
 * Splicing from the root permission route to the current permission route
 * @param {Permission} permission - current permission
 * @param {Permission[]} flattenedPermissions - flattened permission array
 * @param {string} route - parent permission route
 * @returns {string} - The complete route after splicing
 */
function getCompleteRoute(permission: Permission, flattenedPermissions: Permission[], route = '') {
  const currentRoute = route ? `/${permission.route}${route}` : `/${permission.route}`;

  if (permission.parentId) {
    const parentPermission = flattenedPermissions.find((p) => p.id === permission.parentId)!;
    return getCompleteRoute(parentPermission, flattenedPermissions, currentRoute);
  }

  return currentRoute;
}
